import { defineStore } from 'pinia'
import type { EducationalAchievementArticle } from '../../types/YRCG/EducationalAchievementArticle'

/**
 * 育人成果文章存储模块
 * 负责管理育人成果相关文章的全局状态
 */
export const useTeachingPostStore = defineStore('educationalAchievementArticle', {
    // 持久化配置
    persist: {
        storage: localStorage,
        paths: ['articleList', 'currentArticle', ]
    },
    state: () => ({
        // 所有文章列表
        articleList: [] as EducationalAchievementArticle[],
        // 当前选中的文章
        currentArticle: null as EducationalAchievementArticle | null,
        // 加载状态
        loading: false,
        // 分页信息
        pagination: {
            currentPage: 1,
            pageSize: 10,
            total: 0
        }
    }),
    actions: {
        /**
         * 获取文章列表（带分页）
         * @param page - 页码
         * @param size - 每页数量
         */
        async fetchArticles(page: number = 1, size: number = 10) {
            this.loading = true
            try {
                // const res = await articleApi.getArticles(page, size)
                // this.articleList = res.data
                // this.pagination = {
                //     currentPage: page,
                //     pageSize: size,
                //     total: res.total
                // }
            } finally {
                this.loading = false
            }
        },

        /**
         * 获取文章详情
         * @param articleId - 文章ID
         */
        async fetchArticleDetail(EducationalAchievementArticle) {
            this.loading = true
            try {
                this.currentArticle = await EducationalAchievementArticle
            } finally {
                this.loading = false
            }
        },

        /**
         * 创建新文章
         * @param newArticle - 新文章对象
         */
        async createArticle(newArticle: Omit<EducationalAchievementArticle, 'articleId'>) {
            this.loading = true
            try {
                // const created = await articleApi.createArticle(newArticle)
                // this.articleList.unshift(created)
            } finally {
                this.loading = false
            }
        }
    },
    getters: {
        /**
         * 获取热门文章（按发布时间排序）
         */
        popularArticles(state): EducationalAchievementArticle[] {
            return [...state.articleList]
                .sort((a, b) => new Date(b.publishTime).getTime() - new Date(a.publishTime).getTime())
                .slice(0, 5)
        },

        /**
         * 根据作者筛选文章
         * @param authorId - 作者ID
         */
        articlesByAuthor: (state) => (authorId: number) =>
            state.articleList.filter(article => article.authorId === authorId)
    }
})
